package com.openluat.LuatTestServer.service;

import lombok.extern.slf4j.Slf4j;
import org.apache.ftpserver.FtpServer;
import org.apache.ftpserver.FtpServerFactory;
import org.apache.ftpserver.ftplet.Authority;
import org.apache.ftpserver.ftplet.FtpException;
import org.apache.ftpserver.ftplet.UserManager;
import org.apache.ftpserver.listener.ListenerFactory;
import org.apache.ftpserver.usermanager.impl.BaseUser;
import org.apache.ftpserver.usermanager.impl.WritePermission;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import java.io.File;
import java.util.ArrayList;
import java.util.List;

@Configuration
@Slf4j
public class TestFtpConfig {
    @Bean("testFtp")
    public UserManager getUserManger() throws FtpException {

        final String fileDirPathForWindows = "./testftp";
        final String fileDirPathForMacOS = "./testftp";
        final String fileDirPathForLinux = "./testftp";

        String fileDirPath;

        FtpServerFactory serverFactory = new FtpServerFactory();
        ListenerFactory listenerFactory = new ListenerFactory();
        listenerFactory.setPort(21);
        serverFactory.addListener("default", listenerFactory.createListener());

        BaseUser user = new BaseUser();
        user.setName("luat");
        user.setPassword("123456");

        String osName = System.getProperty("os.name");
        log.info("Current OS Name: " + osName);
        if (osName.toLowerCase().startsWith("windows")) {
            fileDirPath = fileDirPathForWindows;
        } else if (osName.toLowerCase().startsWith("linux")) {
            fileDirPath = fileDirPathForLinux;
        } else if (osName.toLowerCase().startsWith("mac")) {
            fileDirPath = fileDirPathForMacOS;
        } else {
            log.error("Get OS Type ERROR");
            return null;
        }

        File fileDir = new File(fileDirPath);
        if (!fileDir.exists()) {
            if (fileDir.mkdirs()) {
                log.info("Create TestFtp FileDir OK");
                user.setHomeDirectory(fileDirPath);
            } else {
                log.error("Create TestFtp FileDir Error");
                return null;
            }
        }

        List<Authority> authorities = new ArrayList<>();
        authorities.add(new WritePermission());
        user.setAuthorities(authorities);
        UserManager userManager = serverFactory.getUserManager();
        userManager.save(user);

        serverFactory.setUserManager(userManager);

        FtpServer testServer = serverFactory.createServer();
        testServer.start();
        log.info("TestFtp start OK");

        return userManager;
    }
}
